package yang.java8.concurrent;

import java.util.concurrent.locks.StampedLock;

public class Vector {
	private int size;
	private Object[] elements;
	private StampedLock lock = new StampedLock();
	
	public Object get(int n) {
		long stamp = lock.tryOptimisticRead();
		Object[] currentElements = elements;
		int currentSize = size;
		if (!lock.validate(stamp)) { // 某个线程持有了一个写锁
			stamp = lock.readLock(); // 获得一个悲观锁
			currentElements = elements;
			currentSize = size;
			lock.unlockRead(stamp);
		}
		return n < currentSize ? currentElements[n] : null;
	}


}
